//api.js
const connection = require('./db')


// 根据用户密码查询用户
const findUserByPassword =async (param) => {
  try {
    let data = await connection.query("select * from user where username = ? and password = ?",param)

    return data[0] // 返回查询结果
} catch (error) {
  throw new Error('查询失败')
}

}

//查询所有用户
const getUser =async () => {
    //第一个参数：sql语句
    //第二个参数：回调函数（err：查询错误，data：查询结果）
    try {
        let data = await connection.query(`select * from user`)
        return data
    } catch (error) {
      throw new Error('查询失败')
    }
}
// 查询单个用户
const findUser = async (username) => {
  // 根据用户ID查询单个用户
  try {
    let data = await connection.query(`select * from user where username = ?`, [username]);
    if (data.length === 0) {
      throw new Error('用户不存在');
    }
    return data; // 返回单个用户对象
  } catch (error) {
    throw new Error('查询失败: ' + error.message);
  }
};
// 根据username删除用户
const deleteUserByUsername = async (username) => {
  try {
    let data = await connection.query(`delete from user where username = ?`, [username]);
    return data; // 返回删除结果
  } catch (error) {
    throw new Error('删除失败: ' + error.message);
  }
};

//添加
const insertUser =async (param) => {

  try {
    let data = await connection.query("insert into user(username,phone) values(?,?)",param);
    return data; // 返回删除结果
  } catch (error) {
    throw new Error('删除失败: ' + error.message);
  }
}
//改
const updateUser = (param) => {
  return new Promise((resolve,reject) => {
    connection.query("update user set username = ? where phone = ?",param,(err,data) => {
      //如果err为null则成功
      resolve(data)
    })
  })
}

//删除
const deleteUser = (param) => {
  return new Promise((resolve,reject) => {
    connection.query("delete from user where id = ?",param,(err,data) => {
      resolve(data)
    })
  })
}
//导出方法，在需要使用到的模块中导入
module.exports = {
  getUser,
  insertUser,
  updateUser,
  deleteUser,
  findUser,
  deleteUserByUsername,
  findUserByPassword
}